package com.logistics.controller.tenant;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.logistics.common.Result;
import com.logistics.common.TenantContextHolder;
import com.logistics.entity.Site;
import com.logistics.entity.SysUser;
import com.logistics.mapper.SiteMapper;
import com.logistics.mapper.SysUserMapper;
import com.logistics.security.JwtTokenProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 站点管理控制器
 */
@RestController
@RequestMapping("/tenant/site")
public class SiteController {
    
    @Autowired
    private SiteMapper siteMapper;
    
    @Autowired
    private SysUserMapper userMapper;
    
    @Autowired
    private JwtTokenProvider jwtTokenProvider;
    
    /**
     * 获取站点列表
     */
    @GetMapping("/list")
    @PreAuthorize("hasAuthority('site:view') or hasAnyRole('SUPER_ADMIN','SITE_ADMIN')")
    public Result<List<Site>> getSiteList() {
        Long tenantId = TenantContextHolder.getTenantId();
        
        LambdaQueryWrapper<Site> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Site::getTenantId, tenantId)
               .eq(Site::getStatus, 1)
               .orderByAsc(Site::getSiteCode);
        
        List<Site> sites = siteMapper.selectList(wrapper);
        return Result.success(sites);
    }
    
    /**
     * 获取当前用户的站点信息
     */
    @GetMapping("/current")
    @PreAuthorize("hasAuthority('site:view') or hasAnyRole('SUPER_ADMIN','SITE_ADMIN')")
    public Result<Site> getCurrentSite(Authentication authentication) {
        Long userId = (Long) authentication.getPrincipal();
        SysUser user = userMapper.selectById(userId);
        
        if (user == null || user.getSiteId() == null) {
            return Result.error("当前用户未关联站点");
        }
        
        Site site = siteMapper.selectById(user.getSiteId());
        if (site == null) {
            return Result.error("站点不存在");
        }
        
        return Result.success(site);
    }
    
    /**
     * 切换站点（仅超级管理员）
     */
    @PostMapping("/switch")
    @PreAuthorize("hasAuthority('site:switch') or hasAnyRole('SUPER_ADMIN')")
    public Result<Map<String, Object>> switchSite(@RequestBody Map<String, Long> request, Authentication authentication) {
        Long siteId = request.get("siteId");
        if (siteId == null) {
            return Result.error("站点ID不能为空");
        }
        
        Long userId = (Long) authentication.getPrincipal();
        Long tenantId = TenantContextHolder.getTenantId();
        
        // 验证站点是否属于当前租户
        Site site = siteMapper.selectById(siteId);
        if (site == null) {
            return Result.error("站点不存在");
        }
        
        if (!site.getTenantId().equals(tenantId)) {
            return Result.error("无权访问该站点");
        }
        
        // 更新用户的当前站点
        SysUser user = userMapper.selectById(userId);
        if (user == null) {
            return Result.error("用户不存在");
        }
        
        user.setSiteId(siteId);
        userMapper.updateById(user);
        
        // 重新生成 JWT Token，包含新的 siteId
        String newToken = jwtTokenProvider.generateToken(
            user.getId(),
            user.getTenantId(),
            user.getSiteId(),
            user.getUsername(),
            user.getRole()
        );
        
        // 返回新的 token 和站点信息
        Map<String, Object> result = new java.util.HashMap<>();
        result.put("token", newToken);
        result.put("siteId", siteId);
        result.put("siteName", site.getSiteName());
        
        return Result.success("站点切换成功", result);
    }
}

